package com.paper.tiger.easy.rpc.center.service;

import com.alibaba.fastjson.JSON;
import com.paper.tiger.easy.rpc.center.common.ServerMap;
import com.paper.tiger.easy.rpc.core.RegisterData;
import com.paper.tiger.easy.rpc.core.ServerType;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

import java.util.List;

/**
 * [简要描述]: 客户端注册请求
 * [详细描述]:
 *
 * @author ZouHaiBo
 * @version 1.0, 2021/6/15 08:51
 * @since JDK 1.8
 */
public class RegisterRequestService implements BaseService
{

    private static final InternalLogger log = InternalLoggerFactory.getInstance(RegisterRequestService.class);

    @Override
    public void service(ChannelHandlerContext ctx, RegisterData data)
    {
        log.info("接收到客户端的请求，请求数据为:{}", JSON.toJSONString(data));
        ServerMap.addChannel(ctx.channel(), data);
        // 通知其他服务，有新的服务注册
        notifyAll(data);

    }

    /**
     * 新注册的数据通知到其他所有的服务
     *
     * @param data
     */
    public void notifyAll(RegisterData data)
    {
        // 需要通知到的channel
        List<Channel> channels = ServerMap.selectChannels(data.getList());
        data.setType(null);
        data.setType(ServerType.NEW_JOIN_SERVICE.getCode());
        for (Channel channel : channels)
        {
            channel.writeAndFlush(data);
        }
    }

}
